#include<iostream>
#include<queue>
#include<string>
#include<unordered_map>

using namespace std;
typedef pair<string,int> PSI;
unordered_map<string,int> hashmap;

int dx[4]={-1,1,0,0};
int dy[4]={0,0,1,-1};
void bfs(string s)
{
	hashmap[s]=0;
	queue<string> q;
	q.push(s);

	while(q.size())
	{
		string s=q.front();
		q.pop();
		int pos=0;
		while(s[pos]!='0') pos++;
		int x=pos/3,y=pos%3;
		for(int i=0;i<4;i++)
		{

			for(int j=0;j<4;j++)
			{
				int a=x+dx[i],b=y+dy[i];
				if(a>=0&&a<=2&&b>=0&&b<=2)
				{
					string next=s;
					int p=3*a+b;
					swap(next[p],next[pos]);
					if(hashmap.find(next)==hashmap.end())
					{
						hashmap[next]=hashmap[s]+1;
						q.push(next);
					}
					if(hashmap.count("123804765"))
					{
						cout<<hashmap["123804765"]<<endl;
						return ;
					}
				} 
			}
		}
	}
}
int main()
{
	string s;cin>>s;

	bfs(s);

}